package com.pure.controller;

import java.io.InputStream;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import com.pure.common.ImportExcelUtil;
import com.pure.common.ReturnData;
import com.pure.common.SysCodeMsg;
import com.pure.db.Product;
import com.pure.service.MallService;

@Controller
public class UploadExcelControl {

	@Resource
	private MallService mallService;

	/**
	 * 描述：通过 jquery.form.js 插件提供的ajax方式上传文件
	 * 
	 * @param request
	 * @param response
	 * @throws Exception
	 */
	@ResponseBody
	@RequestMapping(value = "ajaxUpload.do", method = { RequestMethod.GET, RequestMethod.POST })
	public ReturnData ajaxUploadExcel(HttpServletRequest request, HttpServletResponse response,
			@RequestParam Integer userid) throws Exception {
		MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
		ReturnData returnData = new ReturnData();
		try {
			InputStream in = null;
			List<List<Object>> listob = null;
			MultipartFile file = multipartRequest.getFile("upfile");
			if (file.isEmpty()) {
				throw new Exception("文件不存在！");
			}

			in = file.getInputStream();
			listob = new ImportExcelUtil().getBankListByExcel(in, file.getOriginalFilename());
			List<Product> list = new ArrayList<>();
			// 该处可调用service相应方法进行数据保存到数据库中，现只对数据输出
			for (int i = 0; i < listob.size(); i++) {
				List<Object> lo = listob.get(i);
				Product vo = new Product(); 

				vo.setProductname(String.valueOf(lo.get(0)));
				vo.setDescription(String.valueOf(lo.get(1)));
				vo.setProducttype(String.valueOf(lo.get(2)));
				vo.setUserid(userid);
				vo.setPrice(Double.valueOf(String.valueOf(lo.get(3))));
				list.add(vo);
				// System.out.println("打印信息-->机构:"+vo.getCode()+" 名称："+vo.getName()+"
				// 时间："+vo.getDate()+" 资产："+vo.getMoney());
			}
			Integer count = mallService.insertBatch(list);
			returnData.setData(count);
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
			returnData.setCode(SysCodeMsg.CODE_10000);
			returnData.setMessage(SysCodeMsg.MSG_10000);
		}

		return returnData;
	}

}